package self.hoy.demo.rabbitmq.tx;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import self.hoy.demo.rabbitmq.Constant;
import self.hoy.demo.rabbitmq.util.ConnectionUtils;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 事务提交与回滚
 * @author hyh
 * @date 2020/6/7
 */
public class Send implements Constant {
    public static void main(String[] args) throws IOException, TimeoutException {
        Connection connection = ConnectionUtils.getConnection();
        Channel channel = connection.createChannel();
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        String msg = "this is message from sender with transaction";
        channel.txSelect();
        try {
            channel.basicPublish("", QUEUE_NAME, null, msg.getBytes());
//            int a = 1/0;
            channel.txCommit();
            System.out.println("send message : " + msg);

        } catch (Exception e) {
            System.out.println("send error");
            channel.txRollback();
        }
        channel.close();
        connection.close();
    }
}
